package logic

import (
	"context"
	"errors"
	"math/rand"
	"novel-world/model/cache"
	"time"

	"novel-world/novelrpc/internal/svc"
	"novel-world/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *novelrpc.SendSmsRequest) (*novelrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	s, _ := cache.Rdb.Get(cache.Ctx, "sendSmss"+in.Mobile).Result()
	if s != "" {
		return nil, errors.New("验证码一分钟只能获取一次")
	}
	code := rand.Intn(9000) + 1000
	//sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//if sms.Code != 2 {
	//	return nil, err
	//}
	cache.Rdb.Set(cache.Ctx, "sendSms"+in.Mobile, code, time.Minute*5)
	result, _ := cache.Rdb.Incr(cache.Ctx, "sendNumber"+in.Mobile).Result()
	if result == 1 {
		cache.Rdb.Expire(cache.Ctx, "sendSms"+in.Mobile, time.Minute*5)
	}
	cache.Rdb.Set(cache.Ctx, "sendSmss"+in.Mobile, 1, time.Minute*1)
	return &novelrpc.SendSmsResponse{}, nil
}
